<?
class Page implements ISingleton
{
    protected $_allSource = null;
    protected $_request = null;
    protected static $_instance = null;
    protected $_currentSource = null;
    
    public static function getInstance()
    {
        if (!self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    /**
     * Получаем все записи source
     * 
     * @return SourceRow|null 
     */
    public function getAllSource()
    {
        if ($this->_allSource) {
            return $this->_allSource;
        }
        $row = SourcePeer::getInstance()->fetchAll();
        if ($row->count()) {
            $this->_allSource = $row;
            return $this->_allSource;
        }
        return null;
    }
    
    public function setRequest(Zend_Controller_Request_Abstract $request)
    {
        $this->_request = $request;
    }
    
    public function setSourceKey($key)
    {
        if (SourcePeer::getInstance()->findByKey($key)) {
            $_SESSION['source_key'] = $key;
        }
    }
    
    /**
     * Возвращает объект текущего source
     * 
     * @return SourceRow|null
     * @throws Exception 
     */
    public function getCurrentSource()
    {
        if ($this->_currentSource) {
            return $this->_currentSource;
        }
        
        $source_key = null;
        
        if (isset($_SESSION['source_key']) && !empty($_SESSION['source_key'])) {
            $source_key = $_SESSION['source_key'];
        }
        
        if (!$source_key && $this->_request) {
            $source_key = $this->_request->getActionName();
        }
        
        $select = SourcePeer::getInstance()->select();
        $select->where('`key` = ?', $source_key);
        
        $row = SourcePeer::getInstance()->fetchRow($select);
        if (!$row) {
            throw new Exception('Source ' . $source_key . ' not found');
        }
        
        $this->_currentSource = $row;
        return $this->_currentSource;
    }
}
